import React, { useState, useCallback, useMemo, useEffect } from 'react';
import { Button, Typography, message, Modal, Table, Pagination, Space, Tag,Tooltip } from 'antd';

import BlackSearch from "@/components/Black/BlackSearch";
import { useBlackData } from '@/hooks/useBlackData';
import { BlackItem, removeFromBlacklist } from '@/utils/api/black/black';

const { Title } = Typography;

const BlackList: React.FC = () => {
    const pageSize = 10;
    const {
        blacks,
        total,
        loading,
        searchParams,
        fetchBlacks,
        handleSearch,
        handleReset,
        setLoading
    } = useBlackData({ pageSize });

    const [pagination, setPagination] = useState({
        current: 1,
        pageSize,
    });

    // 初始加载数据
    useEffect(() => {
        fetchBlacks(1, pageSize);
    }, [fetchBlacks, pageSize]);

    // 处理表格分页变化
    const handleTableChange = useCallback((page: number, pageSize?: number) => {
        const newPageSize = pageSize || pagination.pageSize;
        setPagination({
            current: page,
            pageSize: newPageSize,
        });
        fetchBlacks(page, newPageSize, searchParams);
    }, [fetchBlacks, pagination.pageSize, searchParams]);

    // 解除拉黑
    const handleRemoveFromBlacklist = useCallback(async (studentId: number) => {
        Modal.confirm({
            title: "确认解除拉黑",
            content: "确定要解除这名学生的拉黑状态吗？",
            okText: "确认",
            cancelText: "取消",
            onOk: async () => {
                try {
                    setLoading(true);
                    const response = await removeFromBlacklist(studentId);
                    if (response.code === 200) {
                        message.success('解除拉黑成功');
                        fetchBlacks(pagination.current, pagination.pageSize, searchParams);
                    }
                } catch (error) {
                    console.error("解除拉黑失败:", error);
                } finally {
                    setLoading(false);
                }
            }
        });
    }, [fetchBlacks, pagination.current, pagination.pageSize, searchParams, setLoading]);

    // 表格列定义
    const columns = [
        {
            title: '序号',
            key: 'index',
            align: 'center' as const,

            render: (text: any, record: BlackItem, index: number) => {
                return (pagination.current - 1) * pagination.pageSize + index + 1;
            }
        },
        {
            title: '学号',
            dataIndex: 'studentNumber',
            key: 'studentNumber',
            align: 'center' as const,
            render: (studentNumber: string) => studentNumber || '-',
        },
        {
            title: '姓名',
            dataIndex: 'name',
            key: 'name',
            align: 'center' as const,

        },
        {
            title: '性别',
            dataIndex: 'sex',
            key: 'sex',
            align: 'center' as const,

            render: (sex: number) => (
                <Tag color={sex === 0 ? 'pink' : 'blue'}>
                    {sex === 0 ? '女' : '男'}
                </Tag>
            ),
        },
        {
            title: '年龄',
            dataIndex: 'age',
            key: 'age',
            align: 'center' as const,

        },
        {
            title: '年级',
            dataIndex: 'grade',
            key: 'grade',
            align: 'center' as const,
            render: (grade: string) => grade ? `${grade}级` : '-',
        },
        {
            title: '院系',
            dataIndex: 'department',
            key: 'department',
            align: 'center' as const,
            ellipsis: true,
        },
        {
            title: '专业',
            dataIndex: 'major',
            key: 'major',
            align: 'center' as const,
            ellipsis: true,
        },
        {
            title: '拉黑原因',
            dataIndex: 'reason',
            key: 'reason',
            align: 'center' as const,
            ellipsis: true,
            render: (reason: string) => {
                if (!reason) return '-';

                const shouldTruncate = reason.length > 10;
                const displayText = shouldTruncate ? `${reason.substring(0, 10)}...` : reason;

                return (
                    <Tooltip title={shouldTruncate ? reason : null}>
                        <span>{displayText}</span>
                    </Tooltip>
                );
            },
        },
        {
            title: '拉黑时间',
            dataIndex: 'createTime',
            key: 'createTime',
            align: 'center' as const,

            render: (time: string) => new Date(time).toLocaleString(),
        },
        {
            title: '操作',
            key: 'action',
            align: 'center' as const,

            render: (_: any, record: BlackItem) => (
                <Button
                    className="remove-black-btn"
                    size="small"
                    onClick={() => handleRemoveFromBlacklist(record.studentId)}
                >
                    解除拉黑
                </Button>
            ),
        },
    ];

    // 传递给Search组件的属性
    const searchProps = useMemo(() => ({
        onSearch: handleSearch,
        onReset: handleReset,
    }), [handleSearch, handleReset]);

    return (
        <div className="black-list-container" style={{ padding: '5px' }}>
            <BlackSearch {...searchProps} />

            <div style={{
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
                marginBottom: '20px',
                paddingBottom: '10px',
                borderBottom: '1px solid #f0f0f0'
            }}>
                <Title level={4} style={{ margin: 0 }}>黑名单</Title>
            </div>

            <div style={{
                overflowX: 'auto',
                borderRadius: '6px',
                marginBottom: '26px'
            }}>
                <Table
                    columns={columns}
                    dataSource={blacks}
                    rowKey="id"
                    pagination={false}
                    loading={loading}
                    style={{ minWidth: '100%' }}
                    scroll={{ x: 'max-content' }}
                />
            </div>

            <div style={{
                display: 'flex',
                justifyContent: 'flex-end',
                alignItems: 'center'
            }}>
                <Pagination
                    current={pagination.current}
                    pageSize={pagination.pageSize}
                    total={total}
                    showQuickJumper
                    showTotal={(total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条记录`}
                    onChange={handleTableChange}
                    onShowSizeChange={handleTableChange}
                />
            </div>

            <style>{`
                .table-cell {
                    padding: 4px 4px;
                    white-space: nowrap;
                    text-align: center;
                }
                .ant-table-thead > tr > th {
                    position: sticky;
                    top: 0;
                    z-index: 1;
                    background-color: #fafafa;
                    font-weight: 600;
                    text-align: center;
                    padding: 8px 4px;
                }
                
                .ant-table-container {
                    position: relative;
                }
                
                .ant-table-tbody > tr:hover > td {
                    background-color: #f5f5f5;
                }
                
                /* 解除拉黑按钮 */
                .remove-black-btn {
                    padding: 2px 7px !important;
                    height: 30px !important;
                    
                    background: linear-gradient(135deg, #107c41 0%, #33c481 100%) !important;
                    border: none !important;
                    color: #ffffff !important;
                    border-radius: 8px;
                    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
                    box-shadow: 
                        0 2px 4px rgba(0, 0, 0, 0.2),
                        inset 0 1px 0 rgba(255, 255, 255, 0.1);

                    align-items: center;
                    font-weight: 500;
                    font-size: 13px;
                    letter-spacing: 0.3px;
                }

                .remove-black-btn:hover {
                    background: linear-gradient(135deg, #34495e 0%, #56789a 100%) !important;
                    color: #ffffff !important;
                    transform: translateY(-2px);
                    box-shadow: 
                        0 4px 10px rgba(0, 0, 0, 0.25),
                        inset 0 1px 0 rgba(255, 255, 255, 0.15);
                }

                .remove-black-btn:active {
                    background: linear-gradient(135deg, #243342 0%, #3a5674 100%) !important;
                    transform: translateY(0);
                    box-shadow: 
                        0 2px 4px rgba(0, 0, 0, 0.2),
                        inset 0 1px 0 rgba(255, 255, 255, 0.05);
                }

            `}</style>
        </div>
    );
};

export default React.memo(BlackList);